const fs = require('fs');
const path = require('path');

class FileUtils {
  constructor(sourceFileOrDir) {
    this.sourceFileOrDir = sourceFileOrDir || __dirname;
    this.filePaths = [];
    this.inputExt = '.jack';
    this.outputExt = '.my10.xml';
    this._initFilePaths();
  }

  setOutputExt(outputExt) {
    this.outputExt = outputExt;
    this._initFilePaths();
  }

  setInputExt(inputExt) {
    this.inputExt = inputExt;
    this._initFilePaths();
  }

  isSourceDir() {
    const fileInfo = fs.statSync(this.sourceFileOrDir);
    return fileInfo.isDirectory();
  }

  dirName() {
    if (this.isSourceDir()) {
      return path.parse(this.sourceFileOrDir).name;
    }
    return path.parse(this.sourceFileOrDir).dir.split('/').pop();
  }

  getFilePaths() {
    return this.filePaths;
  }

  _initFilePaths() {
    if (this.isSourceDir()) {
      const pattern = new RegExp(`${this.inputExt}$`);
      this.filePaths = fs
        .readdirSync(this.sourceFileOrDir)
        .filter((item) => pattern.test(item))
        .map((item) => ({ input: path.resolve(this.sourceFileOrDir, item) }));
    } else {
      this.filePaths.push({ input: this.sourceFileOrDir });
    }
    this.filePaths.forEach((item) => {
      item.output = this._replaceOutputExt(item.input);
    });
  }

  _replaceOutputExt(input) {
    return input.replace(new RegExp(`${this.inputExt}$`), this.outputExt);
  }
}

const fileUtils = new FileUtils(process.argv[2]);
module.exports.fileUtils = fileUtils;
